var net = require('net');
var app = require('express')()
var uuid = require('uuid')
var bodyParser = require('body-parser')
const connections = {}

function createConnection(options, callback){
  var client = net.connect(options, function() {
      callback(client)
  });
}
app.use(bodyParser.text())
app.all('/create_connection', function(req,resp){
  createConnection(req.query, function(client){
    var cid = uuid.v1()
    connections[cid] = {
        data: [],
        client: client
    }
    client.on('data',function(data){
      console.log(data)
      if (connections[cid]){
        connections[cid]['data'].push(data)
      }
    })
    client.on('close',function(){
      console.log('close')
      connections[cid] = undefined
    })
    client.on('error',function(){
      console.log('error')
      connections[cid] = undefined
    })
    resp.send(cid)
  })  
})

app.all('/send', function(req,resp){
  conn = connections[req.query.cid];
  if(conn){
    var data = Buffer.from(req.body, 'base64')
    conn.client.write(data)
    resp.end()
  }else{
    resp.sendStatus(400)
    resp.send()    
  }
})

app.all('/get_data',function(req,resp){
  conn = connections[req.query.cid];
  if(conn){
      var data = Buffer.concat(conn.data)
      resp.send(data.toString('base64'))
      conn['data'] = []    
  }else{
    resp.sendStatus(400)
  }
  resp.end()
})

app.all('/get_connections',function(req,resp){
  resp.send(JSON.stringify(connections))
})

app.all('/close',function(req,resp){
  conn = connections[req.query.cid];
  if(conn){
    conn['client'].end()
  }else{
    resp.sendStatus(400)
  }
  resp.end()
})
var port = process.argv[2]
port = port ?  port : 8080;
app.listen(port,function(){
  console.log("success,port is " + port);
})

